package com.ias.agdis_r.activity.task;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.adapter.TaskDocListAdapter;
import com.ias.agdis_r.bean.document.Document;
import com.ias.agdis_r.bean.document.DocumentResult;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.util.network.HttpUtil;
import com.ias.agdis_r.manager.BlueToothManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.bill.endpoint.request.BillPrintRequest;
import com.ias.agdis_r.terminalmanager.restful.bill.vo.BillPrintRequestVO;
import com.ias.agdis_r.util.S;

/**
 * 单据列表界面
 *
 * @author guoxr
 */
public class TaskDocListActivity extends BaseActivity implements
        OnClickListener {
    private HashMap<String, Object> taskdata;
    private String fke;// 航班唯一号
    private String fln;// 航班号
    private String aod;// 进离港标识
    private String tnb;// 任务唯一号
    private TaskDocListAdapter adapter;
    private DocumentResult docList;
    private AlertDialog alertDialog;
    private ArrayList<HashMap<String, Object>> mylist = new ArrayList<HashMap<String, Object>>();
    private ListView list;
    private int firstVisiblePosition = 0;
    private int selected = -1;// 选中的记录索引
    private ActionBar actionBar;
    private BillPrintRequest billprintRequest;
    private Task task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_taskdoclist);
        actionBar = getActionBar();
        taskdoclistactionbar();
        Intent intent = getIntent();
        taskdata = (HashMap<String, Object>) intent.getExtras().get("taskdata");
        initGUI();
    }

    private void taskdoclistactionbar() {
        // TODO Auto-generated method stub
        actionBar.setCustomView(LayoutInflater.from(TaskDocListActivity.this)
                .inflate(R.layout.actionbar_back_and_home, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        TextView title = (TextView) findViewById(R.id.txt_title);
        title.setText(R.string.TaskDocListActivity);
        ImageView back = (ImageView) findViewById(R.id.action_back);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        ImageView home = (ImageView) findViewById(R.id.action_home);
        home.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TaskDocListActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    private void initGUI() {
        // TODO Auto-generated method stub
        TextView button_back = (TextView) findViewById(R.id.bottom_button1);
        TextView button_report = (TextView) findViewById(R.id.bottom_button2);
        TextView button_detail = (TextView) findViewById(R.id.bottom_button4);
        button_back.setText(R.string.back);
        button_report.setText(R.string.report);
        button_detail.setText(R.string.detail1);
        // 注册点击事件
        button_back.setOnClickListener(this);
        button_report.setOnClickListener(this);
        button_detail.setOnClickListener(this);
        TextView txt_fln = (TextView) findViewById(R.id.txt_FLN);
        if (taskdata != null) {
            fke = S.valueOf(taskdata
                    .get(MessageModel.strTxtValue[MessageModel.nFKE]));
            fln = S.valueOf(taskdata
                    .get(MessageModel.strTxtValue[MessageModel.nFLN]));
            aod = S.valueOf(taskdata
                    .get(MessageModel.strTxtValue[MessageModel.nAOD]));
            tnb = S.valueOf(taskdata.get(MessageModel.TNB));
            if (aod.equals("A")) {
                txt_fln.setText(getString(R.string.aodA) + fln);
            } else {
                txt_fln.setText(getString(R.string.aodD) + fln);
            }
        }
        if (S.isEmpty(tnb)) {
            button_report.setVisibility(View.GONE);
        }
        loadData();
        bindData();
        // 进入此页面打开蓝牙
        BlueToothManager.getInstance().openBluetooth();
    }

    /**
     * 加载单据数据
     */
    private void loadData() {
        try {

            if (S.isEmpty(fke)) {
                return;
            }
            mylist.clear();
            docList = DataManager.getInstance().getDocList(fke);
            for (Document doc : docList.getDocumentList()) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put(MessageModel.DNM, doc.getBNM());
                map.put(MessageModel.BKE, doc.getBKE());
                map.put(MessageModel.BTP, doc.getBTP());
                map.put(MessageModel.BNO, doc.getBNO());
                map.put(MessageModel.TXT, doc.getTXT());
                if ("S".equals(doc.getSTS())) {
                    map.put(MessageModel.STS, getString(R.string.reported));
                } else {
                    map.put(MessageModel.STS, "");
                }
                mylist.add(map);
            }
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 绑定单据等数据
     */
    private void bindData() {
        try {
            list = (ListView) findViewById(R.id.listview_taskdoclist);
            adapter = new TaskDocListAdapter(TaskDocListActivity.this, mylist);
            list.setAdapter(adapter);
            list.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    view.requestFocusFromTouch();
                    // int index = position-parent.getFirstVisiblePosition() ;
                    firstVisiblePosition = 0;
                    adapter.setSelectItem(position);
                    adapter.notifyDataSetChanged();
                    parent.setSelection(position);
                }
            });
            list.setOnItemSelectedListener(new OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view,
                                           int position, long arg3) {
                    firstVisiblePosition = parent.getFirstVisiblePosition();
                    int index = position - parent.getFirstVisiblePosition();
                    selected = index;
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        loadData();
        if (S.isNotEmpty(tnb)) {
            task = DataManager.getInstance().getWorkTask(tnb);
            if (null == task) {
                finish();
            }else if (task.getPID().equals(MessageModel.TCXX) || task.getPID().equals(MessageModel.TEND) || task.getPID().equals(MessageModel.TRJT)) {
                finish();
            }
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.bottom_button1:
                finish();
                break;
            case R.id.bottom_button2:
                if (alertDialog == null || !alertDialog.isShowing()) {
                    clickBtn2();
                }
                break;
            case R.id.bottom_button3:
                break;
            case R.id.bottom_button4:
                clickBtn4();
                break;
            default:
                break;
        }
    }

    private void clickBtn2() {
        // TODO Auto-generated method stub
        openConfirmWindow();
    }

    private void openConfirmWindow() {
        // TODO Auto-generated method stub
        if (selected == -1 || list.getChildCount() == 0) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
                    getString(R.string.alert_no_choice), false);
            return;
        }
        final HashMap<String, Object> danJuInfoMap = mylist.get(selected);
        String sts = S.valueOf(danJuInfoMap.get(MessageModel.STS));
        if (S.isNotEmpty(sts)) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
                    getString(R.string.docReported), false);
            return;
        }
        AlertDialog.Builder dialogb = new AlertDialog.Builder(this);
        dialogb.setTitle(getString(R.string.reportPrintResult))
                .setIcon(android.R.drawable.ic_dialog_info)
                .setMessage(getString(R.string.docPrintMessage))
                .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        initBLPT(danJuInfoMap.get(MessageModel.BKE).toString(), danJuInfoMap.get(MessageModel.BNO).toString(), danJuInfoMap.get(MessageModel.BTP).toString(), fke);
                        HttpUtil.getInstance().sendRequest(billprintRequest, MessageModel.BLPT, true);
                    }

                    private void initBLPT(String bke, String bno, String btp,
                                          String fkey) {
                        // TODO Auto-generated method stub
                        billprintRequest = new BillPrintRequest();
                        BillPrintRequestVO billprintRequestVO = new BillPrintRequestVO();
                        billprintRequestVO.setBke(bke);
                        billprintRequestVO.setBno(bno);
                        billprintRequestVO.setBtp(btp);
                        billprintRequestVO.setFkey(fkey);
                        billprintRequest
                                .setBillPrintRequestVO(billprintRequestVO);
                    }
                })
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub
                    }
                });
        alertDialog = dialogb.create();
        alertDialog.show();
    }

    private void clickBtn4() {
        // TODO Auto-generated method stub
        if (selected == -1 || list.getChildCount() == 0) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
                    getString(R.string.alert_no_choice), false);
        } else {

            if (S.isEmpty(fln)) {
                EffectManager.getInstance().ttsPlay(
                        EffectManager.TTS_TYPE_UPTO, getString(R.string.flnError), false);
                return;
            }
            HashMap<String, Object> danJuInfoMap = mylist.get(selected);
            String btp = S.valueOf(danJuInfoMap.get(MessageModel.BTP));

            // 跳转到配载单界面
            Intent intent = new Intent(TaskDocListActivity.this,
                    TaskDocDetailActivity.class);
            intent.putExtra(MessageModel.FKE, fke);
            intent.putExtra(MessageModel.BTP, btp);
            intent.putExtra(MessageModel.TNB, tnb);
            intent.putExtra(MessageModel.strTxtValue[MessageModel.nFLN], fln);
            startActivity(intent);
        }
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        // TODO Auto-generated method stub
        if (serviceId.equals(MessageModel.BLRQ)) {
            loadData();
        }
        if (serviceId.equals(MessageModel.BLPT)) {
            loadData();
        }
    }

    @Override
    protected void updateUI(String tag) {
        // TODO Auto-generated method stub
    }

    @Override
    protected void updateUI(String tag, String tnb) {
        if (tag.equals(MessageModel.REFRESH)) {
            if (tnb.equals(this.tnb)) {
                if(MessageModel.TEND.equals(task.getPID()) || MessageModel.TCXX.equals(task.getPID()) || task.getPID().equals(MessageModel.TRJT)){
                    finish();
                }
            }
        }
    }
}
